<template>
  <div>
    <sky/>
    <div style="text-align: center; padding: 10px;min-height: calc(100vh - 3em - 150px);margin-bottom: 150px">
      <div style="margin: 50px 0 40px 0;">
        <h1>
          <a-avatar v-if="userInfo.name" size="large" icon="user" style="background-color:#3b91ff"/>
          {{ userInfo.name }}
        </h1>
        <p v-if="userInfo.name">{{ userInfo.number }}, {{ userInfo.class }},
          <a-dropdown>
          <a class="ant-dropdown-link" @click="e => e.preventDefault()">
            更多 <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a @click="onShowPassword">修改密码</a>
            </a-menu-item>
            <a-menu-item>
              <a style="color: #eb1c25;" @click="loginOut">退出登录</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown></p>
      </div>
      <a-row type="flex" justify="center" :gutter="16">
        <a-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" :xxl="3" style="margin-bottom: 16px">
          <a-card hoverable @click="onShowExam">
            <img
                slot="cover"
                alt="example"
                src="/exam/imgs/exam.png"
            />
            <a-card-meta title="我的比赛" description="查看成绩、比赛">
            </a-card-meta>
          </a-card>
        </a-col>
        <a-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" :xxl="3" style="margin-bottom: 16px" v-if="userInfo.type === 1 || userInfo.type === 2">
          <router-link to="/questions">
            <a-card hoverable>
              <img
                  slot="cover"
                  alt="example"
                  src="/exam/imgs/question.png"
              />
              <a-card-meta title="题库管理" description="新增、修改、删除题目">
              </a-card-meta>
            </a-card>
          </router-link>
        </a-col>
        <a-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" :xxl="3" style="margin-bottom: 16px" v-if="userInfo.type === 1 || userInfo.type === 2">
          <router-link to="/paper">
            <a-card hoverable>
              <img
                  slot="cover"
                  alt="example"
                  src="/exam/imgs/examination.png"
              />
              <a-card-meta title="试卷管理" description="新增、修改、删除比赛">
              </a-card-meta>
            </a-card>
          </router-link>
        </a-col>
        <a-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" :xxl="3" style="margin-bottom: 16px" v-if="userInfo.type === 2">
          <router-link to="/user">
            <a-card hoverable>
              <img
                  slot="cover"
                  alt="example"
                  src="/exam/imgs/user.png"
              />
              <a-card-meta title="用户管理" description="新增、修改、删除用户">
              </a-card-meta>
            </a-card>
          </router-link>
        </a-col>
      </a-row>
    </div>
    <div style="text-align: center;">
      ©2021 Developed in May 2021 by SHY
    </div>

    <a-modal
        :width="1000"
        title="我的比赛"
        :visible="showExams"
        :confirm-loading="false"
        @cancel="()=>{showExams = false}"
        :footer="null"
    >
      <a-list
          class="demo-loadmore-list"
          :loading="loadingExam"
          item-layout="horizontal"
          :data-source="dataExams"
      >
        <div v-if="loadMoreExams" slot="loadMore" :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }">
          <a-button v-if="loadMoreExams && dataExams.length > 0" @click="loadExams" :loading="loadingExam">
            加载更多
          </a-button>
        </div>
        <a-list-item slot="renderItem" slot-scope="exam">
          <router-link :to="'/rank?exam=' + exam.id" slot="actions">
            <a>排行榜</a>
          </router-link>
          <a-list-item-meta :description="exam.info">
            <a-avatar size="large" slot="avatar" :style="{backgroundColor: exam.score > 0 ? '#8fd062': ''}">
              {{exam.score}}
            </a-avatar>
            <h3 slot="title">
              <a-tag :color="tag.color" v-for="(tag, index) in exam.title.tags" v-bind:key="index">{{tag.text}}</a-tag>
              <a v-if="exam.going && !exam.finish" :href="'/exam?exam=' + exam.id">{{exam.title.text}}</a>
              <span v-else>{{exam.title.text}}</span>
            </h3>
          </a-list-item-meta>
          <h3>
            <span>{{ exam.finishCount }}/{{ exam.times }}</span>
          </h3>
        </a-list-item>
      </a-list>
    </a-modal>

    <a-modal title="修改密码(6-20位)" :visible="showPassword" :body-style="{ paddingBottom: '80px' }" ok-text="确定" cancel-text="取消" @ok="onSetPassword" @cancel="onClosePassword" :ok-button-props="{ props: { disabled: !enableSetPassword , loading: btnSubmitLoading} }">
      <a-form-model ref="ruleForm" :model="formData">
        <a-form-model-item required label="旧密码">
          <a-input type="password" v-model="formData.currentPassword" placeholder="请输入旧密码"/>
        </a-form-model-item>
        <a-form-model-item required label="新密码">
          <a-input type="password" v-model="formData.newPassword" placeholder="请输入新密码"/>
        </a-form-model-item>
        <a-form-model-item required label="确认密码">
          <a-input type="password" v-model="formData.reNewPassword" placeholder="请再次输入新密码"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

  </div>
</template>

<script>
import global from "@/components/global";
import sky from "@/components/sky";
import md5 from "js-md5"


export default {
  name: "home",
  components:{
    sky
  },
  data() {
    return {
      args: {
        page: 0,
        size: 10,
      },
      userInfo: {},
      showExams: false,
      dataExams: [],
      loadingExam: false,
      loadMoreExams: true,
      formData:{
        currentPassword: '',
        newPassword: '',
        reNewPassword: ''
      },
      showPassword: false,
      btnSubmitLoading: false
    }
  },
  methods:{
    onSetPassword(){
      let that = this
      this.btnSubmitLoading = true
      global.http(this, 'api/Home/SetPassword', {
        data: {
          oldPassword: md5(that.formData.currentPassword),
          newPassword: md5(that.formData.newPassword)
        },
        successText: '修改成功',
        failText: '修改失败',
        success(){
          that.showPassword = false
        },
        complete(){
          that.btnSubmitLoading = false
        }
      })
    },
    onClosePassword(){
      this.showPassword = false
    },
    onShowPassword(){
      this.formData = {
        currentPassword: '',
        newPassword: '',
        reNewPassword: ''
      }
      this.showPassword = true
    },
    onShowExam(){
      this.args = {
        page: 0,
        size: 10,
      }
      this.dataExams = []
      this.showExams = true
      this.loadExams()
    },
    loginOut(){
      let that = this
      this.$confirm({
        title: '提示',
        content: () => <div>确定要退出登录吗?</div>,
        okText: '确定',
        cancelText: '取消',
        onOk() {
          global.http(that, 'api/Login/LoginOut', {
            successText: '',
            success(){
              window.location = '/login'
            }
          })
        },
      });
    },
    loadExams(){
      let that = this
      that.loadingExam = true
      global.http(this, 'api/Home/ExamInfo', {
        data: that.args,
        successText: '',
        success(res){
          let now = new Date()
          that.dataExams = that.dataExams.concat(...res.data.exams.map(x=>{
            x.title = {text: x.title, tags: []}
            x.going = false
            if(now.getTime() < new Date(x.startTime).getTime()){
              x.title.tags.push({color: 'blue', text: '未开始'})
            }else if(now.getTime() > new Date(x.endTime).getTime()){
              x.title.tags.push({color: 'orange', text: '已结束'})
            }else{
              x.title.tags.push({color: 'green', text: '进行中'})
              x.going = true
            }
            x.info = `${global.dateToMdDay(x.startTime)} ${global.dateToHm(x.startTime)} ~ ${global.dateToHm(x.endTime)} `
            x.info += ` 总分: ${x.fillCount * x.fillScore + x.judgeCount * x.judgeScore + x.radioCount * x.radioScore + x.multipleCount * x.multipleScore} `
            x.info += x.times > 1 ? ` 计分: ${['平均值', '最大值', '最小值'][x.type]}` : ''
            x.papers = res.data.papers.filter(y=>y.examinationId===x.id)
            x.finishCount = x.papers.filter(y=>y.finish).length
            x.finish = x.finishCount >= x.times
            let scores = x.papers.filter(p=>p.finish).map(p=>p.score)
            x.score = [global.mean(scores), global.max(scores), global.min(scores)][x.type]
            return x
          }))
          that.args.page += 1
          that.loadMoreExams = res.data.exams.length >= that.args.size
        },
        complete(){
          that.loadingExam = false
        }
      })
    },
    loadData(){
      let that = this
      global.http(this, 'api/Home/UserInfo', {
        successText: '',
        success(res){
          that.userInfo = res.data.info
          if(res.data.setPassword){
            that.$notification.warning({
              message: '设置密码',
              description:
                  '为了你的账户安全，请尽快设置新的密码。',
            });
          }
        },
        fail(err){
          console.log(err)
        }
      })
    },
  },
  computed:{
    enableSetPassword(){
      return  global.strLenLimit(this.formData.currentPassword, 20, 6) && global.strLenLimit(this.formData.newPassword, 20, 6) && this.formData.newPassword === this.formData.reNewPassword
    }
  },
  mounted() {
    this.loadData()
  }
}
</script>

<style scoped>

</style>